package com.kingsalert.kingsalert.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.kingsalert.kingsalert.analytics.timezone.TimeZoneUtil;
import com.kingsalert.kingsalert.analytics.util.AnalyticsUtil;
import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.activity.ln.MainActivity;
import com.kingsalert.kingsalert.base.BaseActivity;
import com.kingsalert.kingsalert.base.BaseApplication;
import com.kingsalert.kingsalert.bean.userinfo.LoginInfo;
import com.kingsalert.kingsalert.config.PermissionConfig;
import com.kingsalert.kingsalert.dialog.PermissionDialog;
import com.kingsalert.kingsalert.util.UserInfoUtil;
import com.kingsalert.kingsalert.util.http.HttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import pub.devrel.easypermissions.EasyPermissions;

public class LauncherActivity extends BaseActivity {

    private PermissionDialog permissionDialog;

    public static boolean IsNeedCheckSmsPermission = true;//为true:检查短信权限

    private boolean isFirstStart = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);

        page = "LAUNCH";

        findViewById(R.id.al_start).setOnClickListener(v -> startProcess());

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstStart){
            startProcess();
            isFirstStart = false;
        }
    }

    private void startProcess(){
        //1.获取时区配置
        HttpUtil.getInstance().requestTzConfig(this,TimeZoneUtil.INSTANCE.getTimeZoneID(),this::onTZResponse);
    }

    public void onTZResponse(){
        //2.检查权限
        if(isNeedApplyPermission() && (permissionDialog==null||!permissionDialog.isShowing())){
            permissionDialog = new PermissionDialog(this,this::onTZResponse);
            permissionDialog.show();
            return;
        }

        if (permissionDialog!=null && permissionDialog.isShowing()) permissionDialog.dismiss();

        AnalyticsUtil.INSTANCE.init(BaseApplication.getInstant());

        HttpUtil.getInstance().requestAppSInfo(this,this::onAppShowInfoResponse);

    }

    public void onAppShowInfoResponse(){

        //自动登录
        if (UserInfoUtil.getInstance().didLogin()){
            try {
                JSONObject object = new JSONObject();
                object.put("token", UserInfoUtil.getInstance().getToken());
                object.put("userId", UserInfoUtil.getInstance().getUserId());
                object.put("type", UserInfoUtil.LOGIN_TYPE_OLD);
                object.put("isAdSource",UserInfoUtil.getInstance().getIsAdSource() ? "YES":"NO");
                LoginInfo.parse(object);

                AnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo();
                HttpUtil.getInstance().userProcess(this,this::onUserProcessResponse);
                return;
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    private boolean isNeedApplyPermission(){
        //检查PhoneState权限（必须同意）
        if (!PermissionConfig.checkPhonestatePermission(this)) return true;
        //检查Sms权限（每次启动检查一次）
        if (!PermissionConfig.checkSmsPermission(this) && IsNeedCheckSmsPermission){
            IsNeedCheckSmsPermission = false;
            return true;
        }
        return false;
    }

    public void onUserProcessResponse(){
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionDialog!=null) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, permissionDialog);
    }

}